package com.videoaggre.zcl.ui.activity.qiman

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kingja.loadsir.core.LoadService
import com.lxj.xpopup.XPopup
import com.videoaggre.zcl.R
import com.videoaggre.zcl.api.ApiObserver
import com.videoaggre.zcl.api.NotNetworkException
import com.videoaggre.zcl.api.QIMAN_SERVICE
import com.videoaggre.zcl.bean.QimanComicChapter
import com.videoaggre.zcl.bean.QimanComicHomeNormal
import com.videoaggre.zcl.common.changeVisibility
import com.videoaggre.zcl.common.showLoadingCallback
import com.videoaggre.zcl.common.startKtxActivity
import com.videoaggre.zcl.databinding.AgefansItemSerieBinding
import com.videoaggre.zcl.databinding.QimanItemHomeNormalBinding
import com.videoaggre.zcl.db.QimanComicDetail
import com.videoaggre.zcl.db.mQimanDao
import com.videoaggre.zcl.helper.InjectBundle
import com.videoaggre.zcl.helper.loadsir.ErrorCallback
import com.videoaggre.zcl.helper.loadsir.LoadSirHelper
import com.videoaggre.zcl.helper.loadsir.NotNetworkCallback
import com.videoaggre.zcl.parse.impl.QimanParse
import com.videoaggre.zcl.ui.activity.BaseActivity
import com.videoaggre.zcl.ui.activity.launchUI
import com.videoaggre.zcl.ui.adapter.BaseRecyclerAdapter
import com.videoaggre.zcl.ui.adapter.BaseViewHolder
import com.videoaggre.zcl.ui.dialog.QimanSeriesPopup
import com.videoaggre.zcl.utils.FullyGridLayoutManager
import com.videoaggre.zcl.utils.GlideUtils
import com.videoaggre.zcl.utils.Logger
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import kotlinx.android.synthetic.main.qiman_activity_detail.*

class QimanDetailActivity : BaseActivity(R.layout.qiman_activity_detail) {
    companion object {
        fun openDetail(conntext: Context?, id: String) {
            Logger.e("id==>${id}")
            conntext?.startKtxActivity<QimanDetailActivity>(value = "id" to id)
        }
    }

    private val id: String by InjectBundle()
    private val mLoadService: LoadService<*> by lazy { LoadSirHelper.register(rootView) { onReload() } }
    private val mQimanComicRecommendAdapter: QimanComicRecommendAdapter = QimanComicRecommendAdapter()
    private val mQimanComicSerieAdapter: QimanComicSerieAdapter = QimanComicSerieAdapter()
    private val mSeriesPopup: QimanSeriesPopup by lazy {
        XPopup.Builder(this)
            .enableDrag(true)
            .asCustom(QimanSeriesPopup(this)) as QimanSeriesPopup
    }
    private var mQimanComicDetail: QimanComicDetail? = null

    override fun initView() {
        bindViewClick(tvXuanjiMore)
        rvRecommend.layoutManager = FullyGridLayoutManager(this, 2)
        rvRecommend.adapter = mQimanComicRecommendAdapter
        rvSeries.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        rvSeries.adapter = mQimanComicSerieAdapter
        mQimanComicSerieAdapter.setOnClickAdapterListenter(::onClickAdapterSeries)
        mSeriesPopup.onClickAdapterListenter = ::openBrowse
    }

    override fun initData() {
        mLoadService.showLoadingCallback()
        onReload()
    }

    override fun onClick(v: View?) {
        when (v) {
            tvXuanjiMore -> mSeriesPopup.show()
        }
    }

    private fun onClickAdapterSeries(view: View, position: Int) {
        openBrowse(mQimanComicSerieAdapter.getItem(position))
    }

    private fun openBrowse(qimanComicChapter: QimanComicChapter) {
        mSeriesPopup.dismiss()
        QimanBrowseActivity.openBrowse(this, id, qimanComicChapter.id)
    }

    private fun onReload() {
        launchUI({
            mQimanComicDetail = mQimanDao.queryQimanComicDetailById(id)
            if (mQimanComicDetail != null) {
                handQimanComicDetail()
            }
            mQimanComicDetail = QimanParse.parseDetail(id, QIMAN_SERVICE.qimanDetail(id)).also { mQimanDao.addQimanComicDetail(it) }
            handQimanComicDetail()
        }, ApiObserver(loadService = mLoadService, error = {
            (mQimanComicDetail != null).also {
                if (it) {
                    mLoadService.showSuccess()
                }
            }
        }))
    }

    private fun handQimanComicDetail() {
        mQimanComicDetail?.apply {
            titleView.titleStr = name
            GlideUtils.intoView(this@QimanDetailActivity, img, ivCover)
            tvName.text = name
            tvType.text = type
            tvUpdateTime.text = updateTime
            tvLatestChapter.text = latestChapter
            tvDesc.changeText(desc)
            tvAuthor.text = author
            mSeriesPopup.changeSerie(chapters)
            mQimanComicSerieAdapter.datas = chapters
            mQimanComicSerieAdapter.notifyDataSetChanged()
            mQimanComicRecommendAdapter.datas = recommends
            mQimanComicRecommendAdapter.notifyDataSetChanged()
        }
    }
}

class QimanComicSerieAdapter : BaseRecyclerAdapter<BaseViewHolder<AgefansItemSerieBinding>, QimanComicChapter>() {
    override fun onCreateViewHolder(parent: ViewGroup, p1: Int) = BaseViewHolder(AgefansItemSerieBinding.inflate(getLayoutInflate(parent.context), parent, false))
    override fun onBindViewHolder(holder: BaseViewHolder<AgefansItemSerieBinding>, bean: QimanComicChapter, position: Int) {
        holder.mViewBinding.run {
            bean.run {
                cbSerie.text = name
                setViewClick(position, cbSerie)
            }
        }
    }
}

class QimanComicRecommendAdapter : BaseRecyclerAdapter<BaseViewHolder<QimanItemHomeNormalBinding>, QimanComicHomeNormal>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = BaseViewHolder(QimanItemHomeNormalBinding.inflate(getLayoutInflate(parent.context), parent, false))
    override fun onBindViewHolder(holder: BaseViewHolder<QimanItemHomeNormalBinding>, bean: QimanComicHomeNormal, position: Int) {
        holder.mViewBinding.apply {
            bean.apply {
                GlideUtils.intoRoundedCorners(ivImage.context, img, ivImage, roundingRadius = 4, cornerType = RoundedCornersTransformation.CornerType.TOP)
                tvName.text = name
                tvDescName.text = desc
                tvDescName.changeVisibility = desc.isNotEmpty()
                setViewClick(position, root)
            }
        }
    }

    override fun subOnClickAdapter(v: View, position: Int) {
        QimanDetailActivity.openDetail(v.context, getItem(position).id)
    }
}